package com.uminho.egendmeprofessional;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URISyntaxException;
import java.text.ParseException;
import java.util.Calendar;
import java.util.Date;

import org.apache.http.client.ClientProtocolException;
import org.json.JSONException;

import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.Toast;

import com.markupartist.android.widget.ActionBar;
import com.markupartist.android.widget.ActionBar.Action;
import com.uminho.exceptions.DestroyException;
import com.uminho.exceptions.InvalidJSonException;
import com.uminho.exceptions.InvalidOAuthParametersError;
import com.uminho.exceptions.InvalidOAuthTokenError;
import com.uminho.exceptions.NotAllowedError;
import com.uminho.exceptions.OAuthServiceFailureError;
import com.uminho.exceptions.SaveException;
import com.uminho.http.InternalStorage;
import com.uminho.http.Webservice;
import com.uminho.objects.User;

/****c* egendme/Profile
 * DESCRIPTION
 * Classe responsável pela actividade associada ao perfil
 *
 ****
 */

public class Profile extends Activity {
	EditText username, name, mobile_phone, phone,email, address, website,  birth;
	ImageView profilepicture;
	Spinner gender;
	Webservice w;
	User u;
	ProgressDialog myProgressDialog = null; 
	Handler messages;
	Button submitUpdates;
	static final int DATE_DIALOG_ID = 0;

	/****f* Profile/onCreate
	 * DESCRIPTION
	 * Método executado para cria a actividade
	 * INPUTS
	 * Estado da aplicação
	 * RESULT
	 * Actividade criada
	 *
	 ****
	 */
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.profile);
		ActionBar actionBar = (ActionBar) findViewById(R.id.actionbar);
		actionBar.setHomeAction(new Action() {
			
			public void performAction(View view) {
				Intent i = new Intent(Profile.this, Dashboard.class);
				startActivity(i);
			}
			
			public int getDrawable() {
				return R.drawable.icon1;
			}
		});
		actionBar.setTitle(R.string.profile);

		profilepicture = (ImageView)findViewById(R.id.profilepicture);
		username = (EditText) findViewById(R.id.editusername);
		name = (EditText) findViewById(R.id.editprofilename);
		gender = (Spinner) findViewById(R.id.spinnerprofilegender);
		mobile_phone = (EditText) findViewById(R.id.editprofilemobilephone);
		phone = (EditText) findViewById(R.id.editprofilephone);
		email = (EditText) findViewById(R.id.editprofileemail);
		address = (EditText) findViewById(R.id.editprofileaddress);
		website = (EditText) findViewById(R.id.editprofilewebsite);
		birth = (EditText) findViewById(R.id.editprofilebirth);
		submitUpdates = (Button)findViewById(R.id.submitupdates);

		myProgressDialog = ProgressDialog.show(this,getString(R.string.loading), getString(R.string.getprofile), true); 

		new Thread() {

			@Override
			public void run() {
				w = Webservice.getInstance();

				try {
					try {
						u = w.getProfile();
						messages.sendEmptyMessage(1);
					} catch (SaveException e) {
						messages.sendEmptyMessage(0);
						e.printStackTrace();
					} catch (DestroyException e) {
						messages.sendEmptyMessage(0);
						e.printStackTrace();
					}
				} catch (NumberFormatException e) {
					messages.sendEmptyMessage(0);
					e.printStackTrace();
				} catch (MalformedURLException e) {
					messages.sendEmptyMessage(0);
					e.printStackTrace();
				} catch (InvalidJSonException e) {
					messages.sendEmptyMessage(0);
					e.printStackTrace();
				} catch (ParseException e) {
					messages.sendEmptyMessage(0);
					e.printStackTrace();
				} catch (IOException e) {
					messages.sendEmptyMessage(0);
					e.printStackTrace();
				} catch (InvalidOAuthParametersError e) {
					messages.sendEmptyMessage(0);
					e.printStackTrace();
				} catch (InvalidOAuthTokenError e) {
					messages.sendEmptyMessage(-1);
					e.printStackTrace();
				} catch (OAuthServiceFailureError e) {
					messages.sendEmptyMessage(0);
					e.printStackTrace();
				} catch (NotAllowedError e) {
					messages.sendEmptyMessage(0);
					e.printStackTrace();
				} catch (URISyntaxException e) {
					messages.sendEmptyMessage(0);
					e.printStackTrace();
				} catch (JSONException e) {
					messages.sendEmptyMessage(0);
					e.printStackTrace();
				}


				// dismiss the progress dialog
				myProgressDialog.dismiss();


			}

		}.start();


		messages = new Handler() {

			@Override
			public void handleMessage(Message msg) {

				if(msg.what==-1){
					InternalStorage.deleteToken();
					Intent i = new Intent(Profile.this,Login.class);
					i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
					startActivity(i);
				}
				else if(msg.what==0){
					Toast.makeText(Profile.this, getString(R.string.unknownerrorinternetconnection), Toast.LENGTH_LONG).show();
				}else if(msg.what==2){
				Toast.makeText(Profile.this, getString(R.string.profileupdatedwithsuccess), Toast.LENGTH_LONG).show();
			}
				else if(msg.what==1){
					Log.d("name", u.getName());

					profilepicture.setImageDrawable(u.getAvatar());
					username.setText(u.getUsername());
					name.setText(u.getName());
					mobile_phone.setText(u.getMobile_phone());
					phone.setText(u.getPhone());
					email.setText(u.getEmail());
					address.setText(u.getAddress());
					website.setText(u.getWebsite());
					if(u.getBirthday()!=null){
						Date d = u.getBirthday();
						birth.setText( d.getYear()+1900+"-"+d.getMonth()+"-"+d.getDay());
					}

					if (u.getGender()==null)
						gender.setSelection(2);
					else
						switch(u.getGender()){
						case 'M':
							gender.setSelection(0);
							break;

						case 'F':
							gender.setSelection(1);
							break;

						case 'U':
							gender.setSelection(2);
							break;
						}

					birth.setOnTouchListener( new OnTouchListener() {


						public boolean onTouch(View arg0, MotionEvent arg1) {
							showDialog(DATE_DIALOG_ID);
							return true;
						}

					});
				}
			}
		};

		submitUpdates.setOnClickListener(new OnClickListener(){

			public void onClick(View v) {

				myProgressDialog = ProgressDialog.show(Profile.this,getString(R.string.loading), getString(R.string.setprofile), true); 

				new Thread() {

					@Override
					public void run() {
						w = Webservice.getInstance();
						String genderS;
						if(gender.getSelectedItemId()==0)
							genderS = "M";
						else if (gender.getSelectedItemId()==1)
							genderS = "F";
						else genderS="U";

						Log.d("TEST", "setprofile");

						try {
							w.setProfile(name.getText()+"", email.getText()+"",username.getText()+"" , phone.getText()+"", mobile_phone.getText()+"", genderS, birth.getText()+"", website.getText()+"",address.getText()+"", Profile.this);
							messages.sendEmptyMessage(2);
						} catch (ClientProtocolException e) {
							messages.sendEmptyMessage(0);
							e.printStackTrace();
						} catch (IOException e) {
							messages.sendEmptyMessage(0);
							e.printStackTrace();
						} catch (InvalidOAuthParametersError e) {
							messages.sendEmptyMessage(0);
							e.printStackTrace();
						} catch (InvalidOAuthTokenError e) {
							messages.sendEmptyMessage(-1);
							e.printStackTrace();
						} catch (OAuthServiceFailureError e) {
							messages.sendEmptyMessage(0);
							e.printStackTrace();
						} catch (NotAllowedError e) {
							messages.sendEmptyMessage(0);
							e.printStackTrace();
						} catch (JSONException e) {
							messages.sendEmptyMessage(0);
							e.printStackTrace();
						} catch (SaveException e) {
							messages.sendEmptyMessage(0);
							e.printStackTrace();
						} catch (DestroyException e) {
							messages.sendEmptyMessage(0);
							e.printStackTrace();
						}

						myProgressDialog.dismiss();
					}}.start();


			}


		});

	}




	@Override
	protected Dialog onCreateDialog(int id) {
		Calendar calendario = Calendar.getInstance();

		int ano = calendario.get(Calendar.YEAR);
		int mes = calendario.get(Calendar.MONTH);
		int dia = calendario.get(Calendar.DAY_OF_MONTH);

		switch (id) {
		case DATE_DIALOG_ID:
			return new DatePickerDialog(this, mDateSetListener, ano, mes,
					dia);
		}
		return null;
	}

	private DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener() {
		public void onDateSet(DatePicker view, int year, int monthOfYear,
				int dayOfMonth) {
			String data = String.valueOf(year) + "-"
					+ String.valueOf(monthOfYear+1) + "-" + String.valueOf(dayOfMonth);
			Toast.makeText(Profile.this,
					"DATA = " + data, Toast.LENGTH_SHORT)
					.show();
			birth.setText(data);
		}
	};


}
